package com.lzh.healthCode.core;

import com.alibaba.fastjson.JSONObject;
import com.lzh.healthCode.business.entity.ResultBean;
import com.lzh.healthCode.utils.Constants;
import com.lzh.healthCode.utils.HttpRequest;
import com.lzh.healthCode.utils.SM2Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author suYanLong
 * @date 2022年07月11日 16:30
 */
@Slf4j
@Component
public class HttpRequestConfig {

    private static final String SEND_TYPE_GET = "get";

    private static final String SEND_TYPE_POST = "post";

    @Resource
    HealthCodeInfo healthCodeInfo;

    public ResultBean sendPost(String url, String requestParam) {
        return sendData(url, requestParam, healthCodeInfo.getOrgKeyCity(), SEND_TYPE_POST);
    }

    public ResultBean sendPostProvince(String url, String requestParam) {
        return sendData(url, requestParam, healthCodeInfo.getOrgKeyProvince(), SEND_TYPE_POST);
    }

    public ResultBean sendGet(String url, String requestParam) {
        return sendData(url, requestParam, healthCodeInfo.getOrgKeyCity(), SEND_TYPE_GET);
    }

    public ResultBean sendData(String url, String requestParam, String orgKey, String type) {

        // 接口 【参数】【加密】
        String data = SM2Util.encrypt(healthCodeInfo.getProvincePublicKey(), requestParam);

        log.info("加密数据data: {}", data);

        // 接口 【请求头】
        Map<String, Object> headers = new HashMap<>();
        headers.put(Constants.PARAM_KEY_ORG_KEY, orgKey);
        headers.put(Constants.PARAM_KEY_CONTENT_TYPE, Constants.PARAM_VALUE_CONTENT_TYPE);
        String jsonString = JSONObject.toJSONString(headers);
        log.info("转string：{}", jsonString);

        // 接口 【请求体body】
        JSONObject param = new JSONObject();
        param.put(Constants.PARAM_KEY_DATA, data);
        String result = type.equals("post") ? HttpRequest.sendPost(url, param.toString(), headers) : HttpRequest.sendGet(url, param, headers);

        log.info("{}接口返回结果：{}", url, result);
        ResultBean resultBean = JSONObject.parseObject(result, ResultBean.class);

        // 接口 【返回结果】【解密】
        if (!StringUtils.isEmpty(resultBean.getResult())) {
            resultBean.setResult(SM2Util.decrypt(healthCodeInfo.getPrivateKey(), resultBean.getResult()));
        }
        log.info("解密返回数据 实体：{}", resultBean);

        return resultBean;
    }

}
